/**
 * Title: BaseCommonAction.java
 * Description:
 * Copyright: Copyright (c) 2008
 * Company:深圳彩讯科技有限公司
 * Author 罗旭东 (hi@luoxudong.com)
 * Date 2014-2-28 上午9:31:35
 * Version 1.0
 */
package com.bchun.gamepk.web.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;

/** 
 * ClassName: BaseCommonAction
 * Description:TODO(这里用一句话描述这个类的作用)
 * Create by 罗旭东
 * Date 2014-2-28 上午9:31:35
 */
public class BaseCommonAction extends ActionSupport{
	private static final long serialVersionUID = 1L;

	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	public ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}
	
	public HttpSession getSession() {
		return getRequest().getSession();
	}
	
	public void outJsonObject(Object jsonObject)
	{
		Gson gson = new Gson();
		outJsonString(gson.toJson(jsonObject));
	}
	
	public void outJsonString(String str) {
		getResponse().setContentType("text/html;charset=UTF-8");
		System.out.println("下发数据:" + str);
		outString(str);
	}
	
	public void outString(String str) {
		try {
			getResponse().setHeader("Cache-Control", "no-cache");
			getResponse().setCharacterEncoding("UTF-8");
			PrintWriter out = getResponse().getWriter();
			out.write(str);
			out.flush();
			out.close();
		} catch (IOException e) {
		}
		
		//要返回空
	}
	
	/**
	 * 
	 * [Summary]
	 *       getRequestData 获取客户端请求
	 * @param request
	 * @return
	 *
	 */
	public String getRequestData(HttpServletRequest request)
	{
		ServletInputStream inputStream = null;
		BufferedReader reader = null;
		String line = null;
		StringBuilder builder = new StringBuilder();
		
		
		try {
			request.setCharacterEncoding("UTF-8");
			inputStream = request.getInputStream();
			reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
		} catch (IOException e) {
			return null;
		}
		finally{
			if (inputStream != null)
			{
				try {
					inputStream.close();
				} catch (IOException e) {
				}
			}
			
			if (reader != null)
			{
				try {
					reader.close();
				} catch (IOException e) {
				}
			}
		}
		
		return builder.toString();
	}
}
